import {constantRouterMap,asyncRouterMap} from '../../router'

const permRouters = {
    state : {
        routers : constantRouterMap,
        addRouters : []
    },
    mutations : {
        SET_ROUTERS : (state,routers)=>{
            state.addRouters = routers,
            state.routers = constantRouterMap.concat(routers)
        }
    },
    actions : {
        //生成动态路由
        GenerateRoutes({commit},roleCode){
            return new Promise(resolve => {
                let accessedRouters;
                if(roleCode === 'admin'){  //管理权限直接放行
                    accessedRouters = asyncRouterMap;
                }else{
                    accessedRouters = filterAsyncRouter(asyncRouterMap,roleCode); //筛选出包含用户角色的路由
                }
                commit('SET_ROUTERS',accessedRouters);
                resolve();
            })
        }
    }
}


/**
 * 递归获取包含用户角色的路由
 * @param asyncRouterMap 静态路由表
 * @param roleCodes 当前用户角色
 */
function filterAsyncRouter(asyncRouterMap,roleCode){
    const accessedRouters = asyncRouterMap.filter(route =>{  //过滤
        if(route.name && route.name.search('Err') != -1){
            return true;
        }
        if(hasRoles(roleCode,route)){
            return true;
        }else{
            if(route.children && route.children.length){
                route.children = filterAsyncRouter(route.children,roleCode);
                if(route.children.length){
                    return true;
                }
            }else{
                return false;
            }
        }
    })
    return accessedRouters;
}

/**
 * 判断是否存在角色
 * @param {*} roleCode  当前用户角色
 * @param {*} route     路由数组元素
 */
function hasRoles(roleCode,route){
    if(route.meta && route.meta.roles){
        return  route.meta.roles.indexOf(roleCode) >= 0 
    }
    return false;
}

export default permRouters;